/*
 * @Author: hongbin
 * @Date: 2022-11-21 14:12:51
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-24 21:11:15
 * @Description:消息条
 */
import { CSSProperties, FC, useCallback, useEffect, useRef } from "react";
import styled, { css } from "styled-components";
import { flexCenter } from "../../styled";

interface IProps {
    loading: boolean;
    /**
     * 提示信息
     */
    message: string | JSX.Element;
    /**
     * 持续时间 默认 300ms
     */
    duration?: number;
    open: boolean;
    onClose: () => void;
    style?: CSSProperties;
    onConfirm?: () => void;
}

const opacityDuration = 300;

const NotificationBar: FC<IProps> = ({ loading, style, open, duration = 300, message, onClose, onConfirm }) => {
    const timer = useRef<NodeJS.Timeout>();

    useEffect(() => {
        if (open) {
            clearTimeout(timer.current);
            timer.current = setTimeout(() => {
                onClose();
                //不算显示消息条时间
            }, duration + opacityDuration);
        }
    }, [duration, onClose, open]);

    return (
        <Container style={style} open={open}>
            {message}
            {onConfirm ? (
                <button className="closeBtn" onClick={onConfirm}>
                    {loading ? "处理中" : "同意"}
                </button>
            ) : null}
            <button className="closeBtn" onClick={onClose}>
                忽略
            </button>
        </Container>
    );
};

export default NotificationBar;

const Container = styled.div<{ open: boolean }>`
    ${flexCenter};
    justify-content: space-between;
    padding: 0.2vmax 0.5vmax;
    background: #1e5909;
    color: #67d844;
    box-shadow: 0 0 1vmax 0 #1e5908;
    .closeBtn {
        border: none;
        border-radius: 0.3vmax;
        font-size: 1.2vmax;
        padding: 0.3vmax 0.5vmax;
        background: #51aa35;
        color: #154802;
        font-weight: bold;
        cursor: pointer;
        margin: 0 0.2vmax;
    }
    transition: 0.3s;
    position: absolute;
    z-index: 12;
    border-radius: 0.4vmax;
    min-width: 15vmax;
    min-height: 3vmax;
    transform: translateX(200px);
    ${({ open }) =>
        open
            ? css`
                  opacity: 1;
                  transform: translateX(0);
              `
            : css`
                  opacity: 0;
              `}
`;
